﻿using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DeliveryManage.Filter
{
    public class PermissionFilter: ActionFilterAttribute
    {
        //Action方法执行之前执行此方法       
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //DeliveryManage.Model.Sys_User model = null;
            try
            {
                string url = filterContext.HttpContext.Request.Url.AbsolutePath;
                if (url != "/" && url != "/Home/Login" && url != "/Home/LoginPost")
                {
                    //return;
                    if (!IsAdminLogin(filterContext.HttpContext))
                    {
                        //跳转到登陆页    
                        filterContext.HttpContext.Response.Redirect("/Home/Login");
                    }
                }
                ////校验用户是否已经登录 
                //model = filterContext.HttpContext.Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                //if (model == null || model.id <= 0)
                //{   //跳转到登陆页    
                //    filterContext.HttpContext.Response.Redirect("/Home/Login");
                //}
            }
            catch (Exception e)
            {
                filterContext.HttpContext.Response.Redirect("/Home/Login");
            }
        }

        public bool IsAdminLogin(HttpContextBase context)
        {
            //如果Session为Null
            if (context.Session["session_admin_info"] != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = Utils.GetCookie("AdminName", "DeliveryManage");
                string adminpwd = Utils.GetCookie("AdminPwd", "DeliveryManage");
                if (adminname != "" && adminpwd != "")
                {
                    DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                    //把明文进行加密重新赋值
                    adminpwd = ZyEncrypter.GetMd5str(adminname + adminpwd);
                    DeliveryManage.Model.Sys_User model = dal.GetModel(adminname, adminpwd);
                    if (model != null)
                    {
                        context.Session["session_admin_info"] = model;
                        return true;
                    }
                }
            }
            return false;
        }
    }
}